// Server API makes it possible to hook into various parts of Gridsome
// on server-side and add custom data to the GraphQL data layer.
// Learn more: https://gridsome.org/docs/server-api/

// Changes here require a server restart.
// To restart press CTRL + C in terminal and run `gridsome develop`
const axios = require('axios')
const dayjs = require('dayjs')

module.exports = function (api) {
  api.loadSource(async actions => {

  
    const { data: followers } = await axios.get('https://api.github.com/users/GitHub-Laziji/followers')

    const followersCollection = actions.addCollection({
      typeName: 'Follower'
    })

    let followerIndex = 0
    for (const one of followers) {

      followersCollection.addNode({
        index: followerIndex,
        name: one.login,
        id: one.id,
        avatar: one.avatar_url
      })
      followerIndex++
    }


    const { data: followings } = await axios.get('https://api.github.com/users/GitHub-Laziji/following')

    const followingsCollection = actions.addCollection({
      typeName: 'Following'
    })

    let followingIndex = 0
    for (const one of followings) {
      followingsCollection.addNode({
        index: followingIndex,
        name: one.login,
        id: one.id,
        avatar: one.avatar_url
      })
      followingIndex++
    }


    const { data: blogs } = await axios.get('https://api.github.com/users/GitHub-Laziji/gists')

    const blogsCollection = actions.addCollection({
      typeName: 'Blog'
    })

    let blogIndex = 0
    for (const one of blogs) {
      for(const key in one.files){
        blogsCollection.addNode({
          index: blogIndex,
          title: key,
          description: one.description,
          updateTime: dayjs(one.updated_at).format('YYYY-MM-DD HH:mm:ss')
        })
        blogIndex++
      }
    }

    const { data: repos } = await axios.get('https://api.github.com/users/GitHub-Laziji/repos')

    const reposCollection = actions.addCollection({
      typeName: 'Repo'
    })

    let repoIndex = 0
    for (const one of repos) {
      reposCollection.addNode({
        index: repoIndex,
        id: one.id,
        name: one.name,
        license: one['license'] ? one['license']['spdx_id'] : null,
        language: one.language,
        forksCount: one.forks_count,
        watchersCount: one.watchers_count,
        stargazersCount: one.stargazers_count,
        description: one.description,
        url: one.html_url,
        updateTime: dayjs(one.updated_at).format('YYYY-MM-DD HH:mm:ss'),
      })
      repoIndex++
    }
    
  })

  api.createPages(({ createPage }) => {
    // Use the Pages API here: https://gridsome.org/docs/pages-api/
  
  })
}
